﻿var CereriConcediiPage = function(pageContainer) {

    CereriConcediiPage.superclass.constructor.call(this, pageContainer);

    var self = this;
    var scroller = null;
    var Elements = {
        loader: pageContainer.find(".loadMore"),
        cereriContainer: pageContainer.find('.cereriContainer'),
        pullToRefresh: null,
        filtru: pageContainer.find('.filtru'),
        filterButton: pageContainer.find('.filterButton')
    };

    this.Actions = [
        {
            Text: '',
            Callback: function() {
                adaugareCerere();
            },
            CanExecute: function() { return true; }
        }
    ];

    var searchBar = null;
    var searchResultsInfo = null;
    var currentIndex = 0;
    var initialPageSize = 20;
    var pageSize = 10;

    var scrolledPastTop = false;
    var scrolledPastBottom = false;
    var scrollPrevious = 0;
    var isLoading = false;
    var visibleElements = 0;
    var filter = null;
    var cereri = new Array();
    var lastRefreshDate = null;
    var prioritateCurenta = null;
    var searchBarContainer = null;

    var lastData = null;
    var searchTextForCurrentId = null;

    this.closePopups = function() {
        filter.hide();
    };

    var Templates = {
        cerereConcediuTemplate: pageContainer.find("#cerereConcediuTemplate"),
        cerereConcediuTemplateCompiled: null
    };

    var adaugareCerere = function() {
        if (!app.Pages.Cerere.instance)
            app.Pages.Cerere.instance = new CererePage(app.Pages.Cerere.container);
        app.changePage(app.Pages.Cerere);
        if (app.User.IsAlsoEmployee)
            app.Pages.Cerere.instance.setCerere(null, app.User.PRA_ID);
        else app.Pages.Cerere.instance.setCerere(null, null);
    };

    self.initialize = override(self.initialize, function() {
        self.Title = translate('Module_Title_CereriConcediiPage');

        filter = new CereriConcediiFilter(Elements.filtru);
        addSearchBar();
        addResultsInfo(Elements.cereriContainer);
        app.translatePage(app.Pages.CereriConcedii);

        Elements.filtru.bind('apply', function() {
            resetList();
            self.getPullUpData();
        });

        $(document).bind(Events.Cerere_Added, function() {
            resetList();
            self.getPullUpData();
        });

        $(document).bind(Events.Cerere_Modified + ' ' + Events.Cerere_Approved + ' ' + Events.Cerere_Refused, function() {
            resetList();
            self.getPullUpData();
        });

        $(document).bind(Events.Cerere_Deleted, function(e) {
            var ccd_id = e.Data.CCD_ID;
            var elToRemove = Elements.cereriContainer.find(".cerere[data-tm-ccd_id='" + ccd_id + "']");
            if (elToRemove.prev().hasClass('sectiontitle') && elToRemove.next().hasClass('sectiontitle'))
                elToRemove.prev().remove();
            elToRemove.remove();
        });

        pageContainer.bind('onBeforePageShow', function() {
            app.Phone.setBackbtnVisible(!app.HasPageChangedFromMenu);
        });

        pageContainer.bind('onBeforePageHide', function() {
            if (filter && filter.isVisible())
                filter.closeDialogs();
        });

        pageContainer.bind('onPageShow', function() {
            if (filter && filter.isVisible())
                filter.show();
        });

        $(document).bind('changedCompany', function() {
            resetList();
        });
    });

    var addResultsInfo = function(element) {
        element.before($("#searchResultsInfoTemplate").html());
        var searchResultsInfoContainer = pageContainer.find(".search-results-container");
        searchResultsInfo = new SearchResultsInfo(searchResultsInfoContainer);
        searchResultsInfo.hide();
    };

    var addSearchBar = function() {
        pageContainer.find('.content div:first').before($("#searchBarTemplate").html());
        searchBarContainer = pageContainer.find(".search-bar:first");
        searchBar = new SearchBar(searchBarContainer, true, filter);
        searchBar.initialize();
        searchBar.setPlaceholderText(translate('CereriConcediu_Search_Placeholder'));

        searchBarContainer
            .bind('getData', function(e) {
                if (filter.isAnyDialogVisible())
                    return;

                var filterData = filter.getFilterData();
                var isNotNull = false;
                for (i in filterData)
                    if (filterData[i])
                        isNotNull = true;

                searchResultsInfo.hide();
                if (e.Data.reset)
                    resetList();
                filter.hide();
                self.getPullUpData(function(response) {
                    if (response) searchResultsInfo.show(searchBar.getSearchText(), lastData.TotalResults);
                });
            })
            .bind('cancel', function(e) {
                if (filter.isAnyDialogVisible())
                    return;

                searchResultsInfo.hide();
                resetList();
                filter.reset();
                self.getPullUpData();
            })
            .bind('settings', function(e) {
                if (filter.isAnyDialogVisible())
                    return;

                filter.toggle();
            });

        searchBarContainer.show();
    };

    this.setFilterData = function(data, apply) {
        filter.setFilterData(data);
        if (data.id)
            searchTextForCurrentId = searchBar.getCurrentText();

        if (apply) {
            self.showSearchBar();
            searchBar.search();
        }
    };

    this.setSearchData = function(searchText, apply) {
        searchBar.setSearchData(searchText, apply);
    };

    this.refresh = function(all) {
        resetList(all);
        self.getPullUpData();
        return this;
    };

    this.resetFilter = function() {
        filter.reset();
        return this;
    };

    var resetList = function(all) {
        prioritateCurenta = null;
        currentIndex = 0;
        isLoading = false;
        Elements.cereriContainer.empty();
        filter.hide();
        cereri = new Array();
        lastRefreshDate = null;
        lastData = null;
        Elements.loader.show();

        if (all) {
            searchBar.reset(true);
            searchResultsInfo.hide();
        }
    };

    this.getPullDownData = function() {
        resetList();
        lastRefreshDate = new Date();
        Elements.loader.hide();
        self.getPullUpData(function() {
            $(document).trigger('hidePullDown');
        });
    };

    this.getPullUpData = function(callback) {
        if (isLoading)
            return;

        isLoading = true;

        var searchText = searchBar.getSearchText() || "";

        if (searchTextForCurrentId != searchText)
            filter.resetId();

        var noItemsToLoad = currentIndex ? pageSize : initialPageSize;
        var filterData = filter.getFilterData() || {};

        var elm_id = filterData.tipConcediu && filterData.tipConcediu.Tip ? filterData.tipConcediu.Tip.ELM_ID : null;
        var tco_id = filterData.tipConcediu && filterData.tipConcediu.Tip ? filterData.tipConcediu.Tip.TCO_ID : null;
        var stp_id = filterData.tipConcediu && filterData.tipConcediu.Subtip ? filterData.tipConcediu.Subtip.STP_ID : null;

        var status = filterData.statusConcediu ? filterData.statusConcediu.Id : null;
        var pct_id = filterData.punctDeLucru ? filterData.punctDeLucru.Id : null;
        var dpt_id = filterData.punctDeLucru && filterData.departament ? filterData.departament.Id : null;
        var data_start = filterData.dataStart ? moment(filterData.dataStart).format('YYYY/MM/DD') : "";
        var data_sfarsit = filterData.dataSfarsit ? moment(filterData.dataSfarsit).format('YYYY/MM/DD') : "";
        var pra_id_from = filterData.id;
        if (pra_id_from)
            searchText = null;

        app.TMMService.TMM.GetCereriConcediu(currentIndex, noItemsToLoad, searchText, null, elm_id, tco_id, status, pct_id, dpt_id, data_start, data_sfarsit, stp_id, filterData.ignoreSelf, pra_id_from, function(response) {
            isLoading = false;
            Elements.loader.hide();

            if (!response || response.Exception) {
                app.MessagesFactory.showToastWarning(translate('General_Eroare'), translate('General_EroareServer'));
                if (callback)
                    callback(false);
            } else {
                if (currentIndex != response.FinalResult.StartIndex)
                    return;

                if (response.FinalResult.StartIndex == 0)
                    lastData = response.FinalResult;
                else lastData = null;

                var addedIndices = addCereriToList(response.FinalResult.Results, false);

                if (!visibleElements)
                    calculateVisibleElements();

                if (!response.FinalResult.Results.length || (currentIndex == 0 && response.FinalResult.Results.length < visibleElements))
                    Elements.loader.hide();
                else if (!currentIndex)
                    Elements.loader.show();

                if (currentIndex == 0 && response.FinalResult.Results.length)
                    lastRefreshDate = response.FinalResult.Results[0].DataStart;

                currentIndex += (addedIndices || 0);

                if (currentIndex > 0)
                    searchResultsInfo.hide();

                if (callback)
                    callback(true);
            }
        });
    };

    var calculateVisibleElements = function() {
        visibleElements = Math.ceil($(window).height() / Elements.cereriContainer.find(".cerere:first").outerHeight());
    };

    var addCereriToList = function(data, addToStart) {
        if (!data || !data.length)
            return 0;

        if (!Templates.cerereConcediuTemplateCompiled) {
            var source = Templates.cerereConcediuTemplate.html();
            Templates.cerereConcediuTemplateCompiled = Handlebars.compile(source);
        }

        var lastCerere = cereri.length ? cereri[cereri.length - 1] : null;

        var html = "";
        var startIndexInsert = 0;
        for (var i = 0; i < data.length; i++) {
            var c = data[i];
            c.POZA_SRC = Utils.getEmployeePhoto(c.ArePoza ? c.PRS_ID : 0, c.PRS_CNP);
            if (c.Prioritate != prioritateCurenta) {
                prioritateCurenta = c.Prioritate;
                var text = "";
                switch (c.Prioritate) {
                case 0:
                    text = translate('CereriConcediu_Cerere_Urgente');
                    break;
                case 1:
                    text = translate('CereriConcediu_Cerere_Initiate');
                    break;
                case 2:
                    text = translate('CereriConcediu_Cerere_Aprobate');
                    break;
                case 3:
                    text = translate('CereriConcediu_Cerere_Refuzate');
                    break;
                case 4:
                    text = translate('CereriConcediu_Cerere_Finalizate');
                    break;
                }

                html += "<div class='sectiontitle darkblue'>" + text + "</div>";
            }

            switch (c.Prioritate) {
            case 0:
                c.CodCuloare = 'code-orange';
                break;
            case 1:
                c.CodCuloare = 'code-yellow';
                break;
            case 2:
                c.CodCuloare = 'code-green';
                break;
            case 3:
                c.CodCuloare = 'code-gray';
                break;
            case 4:
                c.CodCuloare = 'code-black';
                break;
            }

            c.DataStart = c.DataStart.parseDate();
            c.DataSfarsit = c.DataSfarsit.parseDate();
            if (c.ESTE_ORA) {
                c.DataStartText = Globalize.format(c.DataStart, "e").toString();
                c.DataSfarsitText = Globalize.format(c.DataSfarsit, "e").toString();
                c.NrZileLucratoareText = Utils.getTimeDifferenceText(c.DataStart, c.DataSfarsit);
            } else {
                c.DataStartText = Globalize.format(c.DataStart, "d").toString();
                c.DataSfarsitText = Globalize.format(c.DataSfarsit, "d").toString();
                if (c.DataStart.getFullYear() != c.DataSfarsit.getFullYear()) {
                    var a = c.NrZileLucratoareA;
                    var b = c.NrZileLucratoare - c.NrZileLucratoareA;

                    c.NrZileLucratoareText = a + " + " + b + " " + translate('General_Zile').toLowerCase();
                } else {
                    c.NrZileLucratoareText = c.NrZileLucratoare + " " + (c.NrZileLucratoare == 1 ? translate('General_Zi').toLowerCase() : translate('General_Zile').toLowerCase());
                }
            }
            html += Templates.cerereConcediuTemplateCompiled(c);

            if (!addToStart && lastCerere && lastCerere.CCD_ID == c.CCD_ID) {
                html = "";
                startIndexInsert = i + 1;
            }
        }

        if (startIndexInsert < data.length)
            for (var i = startIndexInsert; i < data.length; i++)
                cereri.push(data[i]);

        if (addToStart) {
            for (var i = data.length - 1; i >= 0; i--)
                cereri.unshift(data[i]);
            Elements.cereriContainer.prepend(html);
        } else Elements.cereriContainer.append(html);

        addActionsOnCerere();

        return data.length - startIndexInsert;
    };

    var addActionsOnCerere = function() {
        Elements.cereriContainer.find('.cerere').unbind().tap(function() {
            if (!app.Pages.Cerere.instance)
                app.Pages.Cerere.instance = new CererePage(app.Pages.Cerere.container);

            var ccd_id = $(this).attr("data-tm-ccd_id");
            app.changePage(app.Pages.Cerere);
            app.Pages.Cerere.instance.setCerere(ccd_id);
        });
    };

    this.showSearchBar = function() {
        if (!searchBarContainer)
            addSearchBar();
        searchBarContainer.show();
        searchBar.show();
        $(document).scrollTop(0);
    };

    this.hideSearchBar = function() {
        searchBarContainer.hide();
        filter.hide();
    };

    var toggleSearchBar = function() {
        if (searchBarContainer.is(":visible"))
            self.hideSearchBar();
        else self.showSearchBar();
    };

    this.setModuleAction = override(self.setModuleAction, function() {
        if (app.Phone)
            app.Phone.setModuleAction(ModuleActions.AddRequest);
    });

    this.goBack = function() {
        if (filter.isAnyDialogVisible())
            return filter.closeDialogs();
        if (filter.isVisible())
            return filter.hide();

        filter.resetId();

        app.changePage(app.getPageByHash(self.LastPageHash));
    };

    this.isAnyDialogOpen = override(self.isAnyDialogOpen, function() {
        if (filter) {
            if (filter.isVisible())
                return true;

            return filter.isAnyDialogVisible();
        }

        return false;
    });
};
extend(CereriConcediiPage, TMMobilePage);